package org.janzen_zhang.androidftp;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;

import java.io.File;
import java.util.Properties;

public class FTPService extends Service {

    private final String TAG = "FTPService";

    private static final int PORT = 8765;

    private FtpServer mFtpServer = null;

    public class FTPBinder extends Binder {

        public FTPService getService(){
            return FTPService.this;
        }

    }

    private FTPBinder binder = new FTPBinder();

    /**
     *
     * @param propertiesFilename 配置文件
     * @param rootPath 挂载的路径
     * @param hostip 本机IP
     */
    private void startFtpServer(String propertiesFilename, String rootPath, String hostip) {
        FtpServerFactory serverFactory = new FtpServerFactory();


        PropertiesUserManagerFactory userManagerFactory = new PropertiesUserManagerFactory();
        File files = new File(propertiesFilename);
        //设置配置文件
        userManagerFactory.setFile(files);
        serverFactory.setUserManager(userManagerFactory.createUserManager());
        // 设置监听IP和端口号
        ListenerFactory factory = new ListenerFactory();
        factory.setPort(PORT);
        factory.setServerAddress(hostip);

        // replace the default listener
        serverFactory.addListener("default", factory.createListener());


        // start the server
        mFtpServer = serverFactory.createServer();
        try {
            mFtpServer.start();
            Log.d(TAG, "start ftpServer");
        } catch (FtpException e) {
            System.out.println(e);
            Log.d(TAG, Log.getStackTraceString(e));
            mFtpServer.stop();
            Log.d(TAG, "occur error, stop server");
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        //挂载的路径
        String storagePath = getPath();
        //配置文件的位置
        String fileName = storagePath + "/AndroidFTP/users.properties";
        //ip
        String ip = getIp();

        Log.d(TAG, "path:" + storagePath);
        Log.d(TAG, "ip:" + ip);
        File file = new File(fileName);
        //if (!file.exists()) {
            //前期工作，复制properties
            CopyFileFromAssets.copy(this, "users.properties", storagePath + "/AndroidFTP", "users.properties");
            //CopyFileFromAssets.copyAssetsDataToSD(this, "users.properties", fileName);
            //修改路径
            PropertiesUtil.put(fileName, "ftpserver.user.anonymous.homedirectory", storagePath);
        //}
        //启动服务
        startFtpServer(fileName, storagePath, ip);
        return binder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        mFtpServer.stop();
        Log.d(TAG, "stop Server");
        return super.onUnbind(intent);
    }

    public String getIp() {
        String ipStr = "";
        //获取wifi服务
        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        //判断wifi是否开启
        if (wifiManager.isWifiEnabled()) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            ipStr = intToIp(ipAddress);
        }

        return ipStr;
    }

    private String intToIp(int i) {

        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }

    /**
     * 获得端口号
     * @return
     */
    public int getPort() {
        return PORT;
    }

    public String getIpAndHost() {
        return getIp() + ":" + PORT;
    }

    /**
     * 获得存储卡的路径
     * @return
     * 如果外置sd卡存在，则返回外置sd卡的路径<br>
     * 否则，返回内置sd卡的路径
     */
    private String getPath() {
        String path = "";
        if (hasSDCard()) {
            path = getSDPath();
        } else {
            path = getInnerSDCardPath();
        }

        return path;
    }

    /**
     * 判断是否存在外置sd卡
     * @return
     */
    private boolean hasSDCard() {
        return Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 获得外置SD卡的路径
     * @return
     */
    private String getSDPath() {
        File sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        return sdDir.toString();

    }

    /**
     * 获取内置SD卡路径
     * @return
     */
    private String getInnerSDCardPath() {
        return Environment.getExternalStorageDirectory().getPath();
    }
}
